
const express = require('express')
var cookieParser = require('cookie-parser');
const cors = require('cors')

const app = express()
const port = 3000

app.use(cors({
  credentials: true,
  origin: 'http://localhost:5500'
}))
// app.all('*',function(req, res, next) {
//   //需要显式设置来源,不能写*
//   res.header("Access-Control-Allow-Origin", req.headers.origin);
//   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
//   res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
//   res.header("Access-Control-Allow-Credentials",true);
// //带cookies
//   res.header("Content-Type", "application/json;charset=utf-8");
//  next();
// });

app.use(cookieParser());
app.use('/public', express.static('public'))

app.post('/login', (req, res) => {
  // maxAge表示cookie存在的有效时长，单位毫秒
  // httpOnly:true表示 前端不能够通过js代码document.cookie去获取cookie的值
  res.cookie('username', 'rose', {maxAge: 10000,httpOnly:true}).send('cookie set');
})


app.get('/user', (req,res) => {
  console.log(req.cookies);
  if(req.cookies.username){
    res.status(200).json({
      message: '访问数据成功',
      statusCode: 200
    })
  } else {
    res.status(401).json({
      message: '未授权',
      statusCode: 401
    })
  }
})
app.listen(port, () => console.log(`Example app listening on port port!`))